package com.tgy.leetcode;

import java.util.Arrays;

/**
 * @Author: tgy
 * @Date: 12/29/20 10:57 AM
 *
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
 */
public class _122_买卖股票的最佳时机_II_01 {

    public int maxProfit(int[] prices) {

        if (prices == null || prices.length <= 1) {

            return 0;
        }

        // 7,1,5,3
        // -7/0

        /**
         *
         *  f(i) -> 买
         *  S(i) 买
         *      S(i) = S(i - 1)买
         *             S(i - 1)卖 + price[i - 1]
         *  S(i) 卖
         *      S(i) = S(i - 1) 卖
         *             S(i - 1)买 - price[i - 1]
         *
         */
        return buyOrSell(prices,0,1, 0);
    }

    private int buyOrSell(int[] prices,int index,int flag, int sum) {

        if (index >= prices.length) {

            return sum;
        }

        int nothing = buyOrSell(prices,index+1,flag,sum);

        int dothing = 0;
        // flag == 1 买
        // flag == 2 卖
        if (flag == 1) {
           dothing = buyOrSell(prices,index+ 1, 2,sum - prices[index]);
        }else if (flag == 2){
           dothing = buyOrSell(prices,index+1,1,sum + prices[index]);
        }

        return Math.max(nothing,dothing);
    }

    public static void main(String[] args) {

        _122_买卖股票的最佳时机_II_01 maxProfit = new _122_买卖股票的最佳时机_II_01();

        int result = maxProfit.maxProfit(new int[]{7, 1, 5, 3, 6, 4});
        System.out.println(result);

    }

}
